/*
 * @Author: QMZhao
 * @Description: 请求接口
 * @Date: 2023-01-05 13:35:31
 * @LastEditTime: 2023-01-07 13:16:00
 * @Reference: 
 */
import { setRequestUrl, errorResponseWrapper, clearParamsWrapper } from "./tools";

type RequestOptions = "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT";

function useRequest(
  url: string,
  method?: RequestOptions,
  params = {},
  header?: Iobj,
  dataType = "json",
  responseType = "text"
): Promise<any> {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${setRequestUrl(url)}`,
      method,
      data: clearParamsWrapper(params),
      sslVerify: false,
      header: { ...header },
      dataType,
      responseType,
      success(successResponse: UniApp.RequestSuccessCallbackResult) {
        const { statusCode, data: responseData } = successResponse;
        const { code, msg } = responseData as AnyObject;
        const successRequestStatusCode = [200, 201, 204];
        if (successRequestStatusCode.includes(statusCode)) {
          // 请求正常
          if (!code) {
            resolve(responseData);
          } else {
            // 接口报错
            uni.showToast({
              title: msg,
              icon: "none",
              mask: true
            });
            reject(responseData);
          }
        } else {
          // http错误
          uni.showToast({
            title: errorResponseWrapper(statusCode),
            icon: "none",
            mask: true,
            success() {
              if (statusCode === 401) {
                setTimeout(() => {
                  uni.navigateTo({
                    url: "/pages/login/index"
                  });
                }, 500);
              }
            }
          });
          reject(responseData);
        }
      },
      fail(failResponse: UniApp.GeneralCallbackResult) {
        console.log("request.fail", failResponse);
        const { errMsg } = failResponse

        console.error('============== 请求异常 ==============')
        console.log('接口地址: ', setRequestUrl(url))
        console.log('接口参数: ', clearParamsWrapper(params))
        console.log('异常信息: ', failResponse)
        console.error('============== 请求异常 end ==========')

        uni.showToast({
          title: errMsg,
          icon: "none",
          mask: true
        });
        reject();
      }
    });
  });
}



export default {
  get<T>(url: string, data: T, header = {}, responseType = undefined) {
    return useRequest(url, "GET", data, header, responseType);
  },
  post<T>(url: string, data: T, header = { "Content-Type": "application/x-www-form-urlencoded" }, responseType = undefined) {
    return useRequest(url, "POST", data, header, responseType);
  }
};

